package com.cdream.basic.algorithm.leetcode.slideWindow;

import java.util.Arrays;

public class Question1838 {
    public int maxFrequency(int[] nums, int k) {
        Arrays.sort(nums);
        int n = nums.length;
        int tempSum = 0;
        int l = 0, res = 1;
        for (int r = 0; r < n; ++r) {
            // [l,r)都调整为num[r]所需要的步数，此时tempSum为[l,r)的和
            while (nums[r] * (r - l) - tempSum > k) {
                tempSum -= nums[l++];
            }
            tempSum += nums[r];
            res = Math.max(res, r - l + 1);
        }
        return res;
    }
}
